﻿using System.Text;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authorization;

namespace JwtAuthenticationForApi.Controllers;
[ApiController]
[Route("/api/auth")]
public class AuthController : ControllerBase
{
    public const string KEY = "oih23rWRG234ofiwoebf02934rfujW$@TGEr";
    [HttpGet]
    [AllowAnonymous]
    public IResult Auth()
    {
        var claims = new List<Claim>()
        {
            new(ClaimTypes.Name,"Admin"),
            new(ClaimTypes.Role,"Administrator"),
            //new(ClaimTypes.Role,"Operator")
        };


        var credential = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KEY)), SecurityAlgorithms.HmacSha256);

        JwtSecurityToken jwtSecurityToken = new(issuer:"", expires: DateTime.Now.AddDays(1), claims: claims, signingCredentials: credential);

        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
        var token = handler.WriteToken(jwtSecurityToken);
        return Results.Ok(token);
    }


    [Authorize(Roles = "Administrator")]
    [HttpGet("info")]
    public IActionResult GetInfo([FromHeader(Name = "Authorization")] string token)
    {
        if (string.IsNullOrEmpty(token))
        {
            return NotFound();
        }

        token = token.Replace("Bearer ", "");

        JwtSecurityTokenHandler handler = new();
        var securityToken = handler.ReadJwtToken(token);


        return Ok(User.Identity.Name);
    }
}
